import java.util.Stack;

public class IsValid {
    // 有效括号序列
    // https://www.nowcoder.com/practice/37548e94a270412c8b9fb85643c8ccc2?tpId=295&tags=&title=&difficulty=0&judgeStatus=0&rp=0&sourceUrl=%2Fexam%2Foj%3Fpage%3D1%26tab%3DSQL%25E7%25AF%2587%26topicId%3D295
    public boolean isValid (String s) {
        // write code here
        Stack<Character> stack = new Stack<>();
        for (char c : s.toCharArray()) {
            if (c == '(' || c == '[' || c == '{') {
                stack.add(c);
            } else {
                if (stack.isEmpty()) {
                    return false;
                }
                char left = stack.pop();
                if ((c == ')' && left != '(')
                        || (c == ']' && left != '[')
                        || (c == '}' && left != '{')) {
                    return false;
                }
            }
        }
        return stack.isEmpty();
    }
}
